package main

import (
	"context"
	"flag"
	"gintest/api"
	"gintest/kernel"
	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
	"net/http"
	_ "net/http/pprof"
	"time"
)
const  DEBUG_ENV ="dev"
const  PRO_ENV ="pro"

func timeoutMiddleware(timeout time.Duration) func(c *gin.Context) {
	return func(c *gin.Context) {

		// wrap the request context with a timeout
		ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)

		defer func() {
			// check if context timeout was reached
			if ctx.Err() == context.DeadlineExceeded {

				// write response and abort the request
				c.Writer.WriteHeader(http.StatusGatewayTimeout)
				c.AbortWithStatus(http.StatusGatewayTimeout)
				//c.Abort()
			}

			//cancel to clear resources after finished
			cancel()
		}()

		// replace request with context wrapped request
		c.Request = c.Request.WithContext(ctx)
		c.Next()
	}
}

func main(){
	go func() {
		http.ListenAndServe("0.0.0.0:6060", nil)
	}()
	var isDebug bool
	flag.BoolVar(&isDebug,"debug",false,"false则未线上环境，true则未开发环境，默认false,线上环境")
	flag.Parse()

	log.Info().Msg("初始化config...")
	if isDebug == true {
		kernel.InitConf(DEBUG_ENV)
	}else{
		kernel.InitConf(PRO_ENV)
	}
	//初始化log
	log.Info().Msg("初始化log...")
	kernel.Initlog()
	r := gin.Default()
	//r := gin.New()
	//自定义变量渲染delimiter ※修改渲染变量包裹符号需要在加载模板文件之前！
	r.Delims("${", "}")
	//设置超时时间
	r.Use(timeoutMiddleware(time.Second * 4))
	//加载模板文件
	r.LoadHTMLGlob("templates/*")
	//加载静态资源路由
	r.Static("/static","D:\\goproject\\src\\gintest\\static")
	r.GET("/", api.Index)

	v1 := r.Group("first")
	{
		v1.GET("/test", api.Test)
		v1.GET("/searchDb", api.SearchDemo)
	}
	//设置http响应时间
	s := &http.Server{
		Addr:           ":8080",
		Handler:        http.TimeoutHandler(r,time.Second * 5,""),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	s.ListenAndServe()
}